import { Component, ViewChild, AfterViewChecked } from '@angular/core';
import { Router, NavigationExtras } from '@angular/router';
import { NgForm } from '@angular/forms';

import { AuthService } from '../../service/AuthService';
import { User } from '../../models/User';


@Component({
    selector: 'app-login',
    templateUrl: 'login.html',
    styleUrls: ['login.css'],
})
export class LoginComponent implements AfterViewChecked {

    user: User;
    loading: Boolean = false;
    messages = {
        username: '',
        password: ''
    };

    @ViewChild('loginForm')
    loginForm: NgForm;

    ngAfterViewChecked() {
        if (this.loginForm) {
            this.loginForm.valueChanges.subscribe(data => this.checkValidate());
        }
    }

    constructor(public authService: AuthService,
                public router: Router) {
        this.user = new User();
    }

    login() {
        this.checkValidate(true);
        if (this.loginForm.invalid) {
            return false;
        }
        this.authService.login(this.user).subscribe((res) => {
            if (res.success) {
                this.authService.user = res.user;

                const redirect: any[] = this.authService.redirectUrl ? ['', {outlets: {primary: this.authService.redirectUrl, auth: null}}]
                    : ['', {outlets: {auth: null}} ];
                const navigationExtras: NavigationExtras = {
                    queryParamsHandling: 'merge',
                    preserveFragment: true
                };

                this.router.navigate(redirect, navigationExtras);

            } else {
                this.messages.password = LoginComponent.ErrorMessages.password.unMatched;
            }
        });

    }


    checkValidate(isSubmit?: boolean) {
        const form = this.loginForm;

        for (const field in LoginComponent.ErrorMessages) {

            const control = form.controls[field];

            if (control && control.valid) {
                this.messages[field] = '';
            }
            if (control && (control.dirty || isSubmit) && !control.valid) {
                const messages = LoginComponent.ErrorMessages[field];
                if (control.errors) {
                    this.messages[field] = messages[Object.keys(control.errors)[0]];
                }
            }

        }
    }

    static ErrorMessages = {
        username: {
            required: '用户名不能为空',
            notExist: '用户名不存在'
        },
        password: {
            required: '密码不能为空',
            unMatched: '用户名密码不匹配'
        }
    };

}
